package com.asktgapp.user.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.asktgapp.MyConstant;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.application.MyApplication;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.eventbus.PayFinishEvent;
import com.asktgapp.model.PayResult;
import com.asktgapp.model.PayVO;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.user.activity.PaySuccessActivity;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.asktgapp.application.MyApplication.mAskEngineerID;
import static com.asktgapp.application.MyApplication.mAskEngineerName;
import static com.asktgapp.application.MyApplication.mAskEngineerHeadIMG;

/**
 * time:2018/1/25
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class PayFragment extends BaseFragment {

    @InjectView(R.id.tv_title)
    TextView mTitle;
    @InjectView(R.id.tv_price)
    TextView mPrice;
    @InjectView(R.id.ll_wx)
    LinearLayout mWxll;
    @InjectView(R.id.ll_ali)
    LinearLayout mAlill;
    @InjectView(R.id.cb_wx)
    CheckBox mCbWx;
    @InjectView(R.id.cb_ali)
    CheckBox mCbAli;
    @InjectView(R.id.tv_pay)
    TextView mPay;
    private double mMoney;
    //0:咨询 1:二手机评估 2:故障代检
    private int payType;
    private String engineerId;
    private String[] PayTitle = {"立即咨询", "专业检车", "故障检测","打赏工程师","上门服务","预付款"};
    private IWXAPI mWxApi;
    private int mAppType = 1;
    private String mAskName,purpose,targetId;
    private int isAskAgain;
    private String mAskEngineerHead;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_pay, container, false);
        ButterKnife.inject(this, viewGroup);
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }


    @Override
    protected void initView(View rootView) {
        getBaseActivity().setBackNavigationIcon();
        Intent intent = getActivity().getIntent();
        mMoney = intent.getDoubleExtra("money", 0);
        engineerId = intent.getStringExtra("eg_user_id");
        mAskName = intent.getStringExtra("name");
        isAskAgain = intent.getIntExtra("isAgain", 0);
        mAskEngineerHead = intent.getStringExtra("eg_pic");
        payType = intent.getIntExtra("type", 0);
        if(payType==5){
            purpose = intent.getStringExtra("purpose");
        }
        if(payType==4){
            targetId= intent.getStringExtra("targetId");
        }
        if (payType <= 5)
            mTitle.setText(PayTitle[payType]);
        mPrice.setText("¥" + mMoney);
        mWxll.setOnClickListener(this);
        mAlill.setOnClickListener(this);
        mPay.setOnClickListener(this);
    }

    @Override
    public void loadData() {

    }


    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        ButterKnife.reset(this);
        super.onDestroyView();

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_wx:
                mCbWx.setChecked(true);
                mCbAli.setChecked(false);
                mAppType = 1;
                break;
            case R.id.ll_ali:
                mCbWx.setChecked(false);
                mCbAli.setChecked(true);
                mAppType = 0;
                break;
            case R.id.tv_pay:
                mPay.setClickable(false);
                //// TODO: 2018/3/5  后面要注释掉
                MyApplication.mAskType = payType;
                mAskEngineerID = engineerId;
                mAskEngineerName = mAskName;
                mAskEngineerHeadIMG = mAskEngineerHead;
                MyApplication.isAskAgain = isAskAgain;
//                startActivity(new Intent(getActivity(), PaySuccessActivity.class));

                Apiservice apiservice = ApiUtil.getInstance().create();
                HashMap params = new HashMap();
                params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
//                类型 0:咨询 1:二手机评估 2:故障代检3:打赏 4上门服务支付  5预付款
                params.put("type", payType);
//                MyApplication.mAskType = payType;
                params.put("eg_user_id", engineerId);
//                mAskEngineerID = engineerId;
                params.put("money", mMoney);
//                params.put("money", "0.01");
                if(payType==5){
                    params.put("purpose",purpose);
                }
                   if(payType ==3){
                    params.put("purpose","打赏");
                }
                if(payType==4){
                    params.put("targetId",targetId);
                }
                //0:支付宝 1:微信
                if (mCbWx.isChecked()) {
                    params.put("pay_type", 1);
                } else {
                    params.put("pay_type", 0);
                }
                showProgress(getClass().getSimpleName());
                Call<ApiResponseBody<PayVO>> call = apiservice.pay(params);
                call.enqueue(new Callback<ApiResponseBody<PayVO>>() {
                    @Override
                    public void onResponse(Call<ApiResponseBody<PayVO>> call, Response<ApiResponseBody<PayVO>> response) {

                        if (response.isSuccessful()) {
                            PayVO bean = response.body().getResult();
                            dealResult(bean);
                            getActivity().setResult(Activity.RESULT_OK);

                        } else {
                            dismissProgress();
                            showTost(response.raw().message(), 0);
                        }
                    }

                    @Override
                    public void onFailure(Call<ApiResponseBody<PayVO>> call, Throwable t) {
                        dismissProgress();
                        ApiException apiException = ExceptionHandle.handleException(t);
                        if (apiException.isTokenInvalid()) {
                            showUnLoginSnackbar();
                        } else if (apiException.isNetConnected()) {
                            showSetNetworkSnackbar();
                        } else {
                            showTost(apiException.getMessage(), 0);
                        }
                    }
                });

                break;
        }
    }

    private void dealResult(PayVO bean) {

        if (mCbWx.isChecked()) { //微信支付
            //AppConst.WEIXIN.APP_ID是指你应用在微信开放平台上的AppID，记得替换。
            mWxApi = WXAPIFactory.createWXAPI(getActivity(), MyConstant.WEIXIN_AppID, false);
            // 将该app注册到微信
            mWxApi.registerApp(MyConstant.WEIXIN_AppID);
            sendPayRequset(bean);
            dismissProgress();
        } else { //支付宝支付

            sendPayRequset(bean);
            dismissProgress();
        }
    }

    private void sendPayRequset(final PayVO bean) {
        if (mAppType == 1) {
            PayReq req = new PayReq();
            req.appId = bean.getAppid();
            req.partnerId = bean.getPartnerid();
            //预支付订单
            req.prepayId = bean.getPrepayid();
            req.nonceStr = bean.getNoncestr();
            req.timeStamp = bean.getTimestamp() + "";
            req.packageValue = "Sign=WXPay";
            req.sign = bean.getSign();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            //3.调用微信支付sdk支付方法
            mWxApi.sendReq(req);
//            startActivity(new Intent(getActivity(), PaySuccessActivity.class));


        } else {
            Runnable payRunnable = new Runnable() {
                @Override
                public void run() {
                    PayTask alipay = new PayTask(getActivity());
                    Map<String, String> result = alipay.payV2(bean.getAlipay(), true);
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }

    }

    private static final int SDK_PAY_FLAG = 1001;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    //同步获取结果
                    String resultInfo = payResult.getResult();
                    Log.i("Pay", "Pay:" + resultInfo);
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (resultStatus.equals("9000")) {
                        startActivity(new Intent(getActivity(), PaySuccessActivity.class));
                        getActivity().finish();
                    } else {
                        Toast.makeText(getActivity(), "支付失败", Toast.LENGTH_SHORT).show();
                        getActivity().finish();
                    }
                    break;
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
//        mPay.setClickable(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void a(PayFinishEvent b) {
        if (b.getType()) {
            if (getActivity() != null) {
                getActivity().finish();
            }
        } else {
            if (mPay != null) {
                mPay.setClickable(true);
            }
        }
    }
}
